﻿<template>
  <el-dialog
    :title="!dataForm.id ? $t('handle.add') : $t('handle.update')"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <div v-loading = loading>
    <el-form :model="dataForm"  :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="150px">
      <el-form-item label="所属上级" prop="parentId" style="width:88%;">
        <el-input v-model="dataForm.parentName" :disabled="true" placeholder="上级"></el-input>
      </el-form-item>
      <el-form-item label="所属小区" prop="address" clearable v-if="superAdmin == 1">
        <!-- <el-select v-model="dataForm.housingEstateId"  filterable  placeholder="请选择" style="width:100%">
          <el-option
          v-for="(item,index) in selectHousingEstate"
          :key="index"
          :label="item.fullName"
          :value="item.id">
          </el-option>
        </el-select> -->
        <el-cascader
          @visible-change.native="test"
          @click.native="getOne"
          placeholder="请选择小区"
          :change-on-select="false"
          v-model="address"
          :options="options"
          :show-all-levels="true"
          @active-item-change="getNodes"
          style="width:86%;"
          :props="props">
        </el-cascader>
      </el-form-item>
       <el-row>
        <el-col :span="12">
          <el-form-item label="服务名称" prop="name">
            <el-input v-model="dataForm.name"  placeholder="名称" style="width:200px;"></el-input>
          </el-form-item>
        </el-col>
         <el-col :span="12">
          <el-form-item label="跳转路径" prop="path">
            <el-input v-model="dataForm.path"  placeholder="跳转路径" style="width:200px;"></el-input>
          </el-form-item>
         </el-col>
       </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="登录使用" prop="isAuth">
            <el-switch
              v-model="dataForm.isAuth"
              :active-text="switchIsAuth.activeText"
              :active-value="switchIsAuth.activeValue"
              :inactive-text="switchIsAuth.inactiveText"
              :inactive-value="switchIsAuth.inactiveValue"
            >
            </el-switch>
          </el-form-item>
        </el-col>
         <el-col :span="12">
          <el-form-item label="首页展示" prop="showIndex">
            <el-switch
              v-model="dataForm.showIndex"
              :active-text="switchshowIndex.activeText"
              :active-value="switchshowIndex.activeValue"
              :inactive-text="switchshowIndex.inactiveText"
              :inactive-value="switchshowIndex.inactiveValue"
            >
            </el-switch>
          </el-form-item>
         </el-col>
      </el-row>
      <!-- <el-form-item label="类型" prop="type">
        <el-select v-model="dataForm.type" filterable :disabled="true"  placeholder="请选择" style="width:100%">
          <el-option
            v-for="(item,index) in selectType"
            :key="index"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
      </el-form-item> -->
        <el-row>
        <el-col :span="12">
         <el-form-item :label="$t('status.status')" prop="status">
        <el-select v-model="dataForm.status" filterable  placeholder="请选择" style="width:190px;">
          <el-option
            v-for="(item,index) in selectStatus"
            :key="index"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
      </el-form-item>
        </el-col>
         <el-col :span="12">
          <el-form-item :label="$t('tabble.sort')" prop="sort">
              <el-input v-model="dataForm.sort" type="number"  placeholder="排序" style="width:195px;"></el-input>
            </el-form-item>
         </el-col>
      </el-row>
      <el-form-item label="图标" prop="icon">
        <el-upload
          ref="upload"
          action="/clientauth/client/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSucess"
          :on-error="handleError"
          :on-exceed="handleExceed"
          :before-upload="beforeAvatarUpload"
          :file-list="fileList"
          :headers="headers"
          :limit="1"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">建议上传宽高为64x64像素的png背景透明图片，且大小不能超过200KB</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div style="text-align:right;">
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
    </span>
    </div>
  </div>
  </el-dialog>
</template>

<script>
import Vue from "vue";
import {
  getOne,
  getTwo,
  getThree,
  getFour,
  getFive,
  getSix
} from "@/utils/questUtils";
import { imgUrlHost } from "@/config/env";
export default {
  data() {
    let checkA = (rule, value, callback) => {
      if (this.address.length === 0) {
        return callback(new Error("社区不能为空"));
      } else {
        return callback();
      }
    };
    return {
      loading: false,
      visible: false,
      imgUrlHost: "",
      superAdmin: sessionStorage.getItem("superAdmin"),
      options: [{}],
      address: [],
      props: {
        value: "id",
        label: "name",
        children: "children"
      },
      headers: {
        Authorization: "Bearer " + Vue.cookie.get("access-token")
      },
      fileList: [],
      picJson: { url: "" },
      dataForm: {
        id: "",
        parentId: "",
        parentName: "",
        name: "",
        icon: "",
        housingEstateId: "",
        type: "",
        path: "",
        status: "",
        showIndex: "",
        sort: "",
        isAuth: ""
      },
      switchshowIndex: {
        activeText: "",
        activeValue: "",
        inactiveText: "",
        inactiveValue: ""
      },
      switchIsAuth: {
        activeText: "",
        activeValue: "",
        inactiveText: "",
        inactiveValue: ""
      },
      selectStatus: [],
      selectType: [],
      selectHousingEstate: [],
      showFalg: false,
      dataRule: {
        parentId: [
          { required: true, message: "上级不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "服务名称不能为空", trigger: "blur" }
        ],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
        path: [
          { required: true, message: "服务跳转路径不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "服务状态不能为空", trigger: "blur" }
        ],
        address: [{ validator: checkA, required: true, trigger: "blur" }]
      }
    };
  },
  methods: {
    init(id, parentId, parentName, type) {
      this.imgUrlHost = imgUrlHost;
      this.getServiceType();
      this.getServiceStatus();
      this.getServiceIsAuth();
      this.getServiceShowIndex();
      this.getHousingEstate();
      // this.dataForm.isAuth = '2'
      // this.dataForm.showIndex = '2'
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.dataForm.isAuth = "2";
        this.dataForm.showIndex = "2";
        this.fileList = [];
        this.dataForm.parentId = parentId;
        this.dataForm.parentName = parentName;
        this.dataForm.type = type.toString();
        this.dataForm.id = id || 0;
        if (this.dataForm.id) {
          this.$http({
            // url: this.$http.adornUrl(`/ic/appservice/info/${this.dataForm.id}`),
            url: `/dg-ic/ic/appservice/info/` + this.dataForm.id,
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.fileList = [{ url: "" }];
              this.dataForm.parentId = data.appService.parentId;
              this.dataForm.name = data.appService.name;
              this.dataForm.icon = data.appService.icon;
              this.dataForm.type = data.appService.type.toString();
              this.dataForm.housingEstateId = data.appService.housingEstateId;
              // this.address = data.appService.housingEasteName
              this.options = [
                {
                  id: data.appService.housingEstateId,
                  name: data.appService.housingEasteName
                }
              ];
              this.address = [data.appService.housingEstateId];
              this.dataForm.path = data.appService.path;
              this.dataForm.status = data.appService.status.toString();
              this.dataForm.isAuth = data.appService.isAuth.toString();
              this.dataForm.showIndex = data.appService.showIndex.toString();
              this.dataForm.sort = data.appService.sort;
              this.dataForm.parentName = data.appService.parentName;
              this.fileList[0].url = this.imgUrlHost + data.appService.icon;
            }
          });
        }
      });
    },
    getServiceType() {
      this.$http({
        // url: this.$http.adornUrl(`/ic/dict/type/service_type`),
        url: "/dg-ic/ic/dict/type/service_type",
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.selectType = data.data;
        }
      });
    },
    getServiceIsAuth() {
      this.$http({
        // url: this.$http.adornUrl(`/ic/dict/type/service_isauth`),
        url: "/dg-ic/ic/dict/type/service_isauth",
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.switchIsAuth.activeText = data.data[1].label;
          this.switchIsAuth.activeValue = data.data[1].value;
          this.switchIsAuth.inactiveText = data.data[0].label;
          this.switchIsAuth.inactiveValue = data.data[0].value;
        }
      });
    },
    getServiceShowIndex() {
      this.$http({
        // url: this.$http.adornUrl(`/ic/dict/type/service_showindex`),
        url: "/dg-ic/ic/dict/type/service_showindex",
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.switchshowIndex.activeText = data.data[0].label;
          this.switchshowIndex.activeValue = data.data[0].value;
          this.switchshowIndex.inactiveText = data.data[1].label;
          this.switchshowIndex.inactiveValue = data.data[1].value;
        }
      });
    },
    getServiceStatus() {
      this.$http({
        // url: this.$http.adornUrl(`/ic/dict/type/service_status`),
        url: "/dg-ic/ic/dict/type/service_status",
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.selectStatus = data.data;
        }
      });
    },
    getHousingEstate() {
      this.$http({
        // url: this.$http.adornUrl(`/ic/dict/type/service_status`),
        url: "/dg-ic/ic/housing-estate/list",
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.selectHousingEstate = data.data.list;
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.loading = true;
          this.$http({
            // url: this.$http.adornUrl(`/ic/appservice/${!this.dataForm.id ? 'save' : 'update'}`),
            url: `/dg-ic/ic/appservice/${
              !this.dataForm.id ? "save" : "update"
            }`,
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              parentId: this.dataForm.parentId,
              name: this.dataForm.name,
              icon: this.dataForm.icon,
              type: this.dataForm.type,
              path: this.dataForm.path,
              status: this.dataForm.status,
              isAuth: this.dataForm.isAuth,
              showIndex: this.dataForm.showIndex,
              sort: this.dataForm.sort,
              createBy: this.$store.state.user.id,
              updateBy: this.$store.state.user.id,
              housingEstateId:
                sessionStorage.getItem("superAdmin") == 1
                  ? this.address[this.address.length - 1]
                  : sessionStorage.getItem("thiscommunityId")
              //this.dataForm.housingEstateId
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.loading = false;
                  this.visible = false;
                  this.$emit('refreshDataList')
                  if (!this.dataForm.id) {
                    // 添加当前节点
                    this.global.refreshNode(this.global.treeNode);
                  } else {
                    //更新  刷新父节点
                    this.global.refreshNode(this.global.treeNode.parent);
                  }
                }
              });
            } else {
              this.$message.error(data.msg);
              this.loading = false;
            }
          });
        }
      });
    },
    handleRemove(file, fileList) {},
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {},
    // 文件上传成功时调用
    handleSucess(response, file, fileList) {
      this.$message({
        message: "文件上传成功",
        type: "success",
        duration: 1500,
        onClose: () => {
          this.dataForm.icon = response.iconName;
          // this.picJson.url = this.dataForm.picUrl
          // this.fileList[0] = this.picJson
        }
      });
    },
    // 文件上传失败时调用
    handleError(file, fileList) {
      this.$message.error("文件上传失败");
    },
    handleExceed(files, fileList) {
      this.$message.error("只能上传一个文件,请先去除原文件");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      let fileFlag = false;
      if (isPNG) {
        fileFlag = true;
      } else {
        this.$message.error("上传头像图片只能是  PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      // * ***************************
      // const isSize = new Promise(function (resolve, reject) {
      //   let width = 64 // 限制图片尺寸为654X270
      //   let height = 64
      //   let _URL = window.URL || window.webkitURL
      //   let img = new Image()
      //   img.onload = function () {
      //     let valid = img.width === width && img.height === height
      //     valid ? resolve() : reject(new Error(0))
      //   }
      //   img.src = _URL.createObjectURL(file)
      // }).then(() => {
      //   return file
      // }, () => {
      //   this.$message.error('图片尺寸限制为64 x 64')
      //   return Promise.reject(new Error(0))
      // })
      return fileFlag && isLt2M; //&& isSize
    },

    // 一级
    getOne() {
      getOne().then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options = response.data.page;
        }
      });
    },
    // 二级
    getTwo(countryId) {
      getTwo(countryId).then(response => {
        if (response.data.page && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map(item => {
            if (item.id === countryId) {
              item.children = response.data.page;
            }
          });
        }
      });
    },
    getThree(countryId, provinceId) {
      getThree(provinceId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((city, id) => {
                city.children = response.data.page;
              });
            }
          });
        }
      });
    },
    getFour(countryId, provinceId, cityId) {
      getFour(cityId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    city.children = response.data.page;
                  });
                }
              });
            }
          });
        }
      });
    },
    getFive(countryId, provinceId, cityId, areaId) {
      getFive(areaId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        area.children = response.data.page;
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getSix(countryId, provinceId, cityId, areaId, communityCodeId) {
      getSix(communityCodeId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        if (area.id === areaId) {
                          area.children.map((communt, ic) => {
                            communt.children = response.data.page;
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getNodes(val) {
      if (val.length === 1) {
        // 获取省
        this.getTwo(val[0]);
      } else if (val.length === 2) {
        // 市
        this.getThree(val[0], val[1]);
      } else if (val.length === 3) {
        // 区
        this.getFour(val[0], val[1], val[2]);
      } else if (val.length === 4) {
        this.getFive(val[0], val[1], val[2], val[3]); //社区
      } else if (val.length === 5) {
        this.getSix(val[0], val[1], val[2], val[3], val[4]); // 小区
      }
      //如果继续添加下级，类似这样继续添加即可
    }
  }
};
</script>

<style>
/* < ! --.el-select .el-input__inner {
    width: 185px;
} --> */
.el-switch {
  width: 210px;
}
.custom-3E8EF7 .el-upload-list--picture .el-upload-list__item {
  width: 86%;
}
</style>

